package com.hk.app.utils;

import com.hk.api.ValidateService;
import com.hk.api.exceptions.ValidateException;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.JsonResult;
import com.hk.commons.vo.yingmi.TerminalRequestDTO;
import com.hk.service.sys.ISysUser;
import com.hk.service.yingmi.impl.YingmiApiRepository;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * Created by Antinomy on 17/8/24.
 */
@Service
public class YingmiOpenAPI {
    private Logger logger = LoggerFactory.getLogger(YingmiOpenAPI.class);

    @Autowired
    public YingmiApiUtils utils;

    @Autowired
    private ISysUser sysUser;

    @Autowired
    private YingmiApiRepository yingmiApiRepo;


    public String sslGet(String path, String params, String flag) {
        getLogging(path, params, flag);

        Map<String, String> map = new HashMap<>();

        if (params != null) {
            String[] s = params.split(";");

            Stream.of(s).map(m -> m.split("=")).forEach(f -> map.put(f[0], f[1]));
        }

        String result = processHttpGet(path, map);
        return result;
    }

    public String sslGet_ByMap(String path, Map<String, String> params, String flag) {
        if(params != null){
            getLogging(path, params.toString(), flag);
        }

        String result = processHttpGet(path, params);
        return result;
    }

    public HashMap convertToMap(String jsonStr) throws IOException {
        HashMap result = new ObjectMapper().readValue(jsonStr, HashMap.class);
        return result;
    }

    public void processJsonResult(JsonResult jsonResult, String json) throws IOException {
        if (StringUtils.isBlank(json))
            return;

        if (isJsonArray(json)) {
            ArrayList result = convertArrayToList(json);

            jsonResult.result = result;
            return;
        }

        HashMap map = convertToMap(json);
        jsonResult.result = map;

        renderErrorCode(jsonResult, map);
    }

    public void renderErrorCode(JsonResult jsonResult, Map map) {
        if (map.get("code") != null && map.get("msg") != null) {
           jsonResult.resultCode = map.get("code").toString();
           jsonResult.msg = map.get("msg").toString();
        }
    }

    public boolean isJsonArray(String json) {
        if (StringUtils.isBlank(json))
            return false;

        return json.startsWith("[") && json.endsWith("]");
    }

    public ArrayList convertArrayToList(String json) throws IOException {
        JSONArray jsonArray = new JSONArray(json);
        ArrayList result = new ArrayList();

        for (Object one : jsonArray) {
            JSONObject jsonpObject = (JSONObject)one;
            Map oneMap = convertToMap(jsonpObject.toString());
            result.add(oneMap);
        }
        return result;
    }

    public String sslPost(Map<String, String> map) {
        String path = map.get("path");
        map.remove("path");

        String result = processHttpPost(map, path);

        return result;
    }

    public String sslPost(String path,  Map<String, String> map) {
        String result = processHttpPost(map, path);

        return result;
    }

    public SysUser getValidatedUser(Long userId, ValidateService validate) {
        validate.check("userId", userId);

        SysUser user = sysUser.findById(userId);

        if(user == null)
            throw new ValidateException("无效用户");
        return user;
    }

    public void applyTerminalInfo(Map<String, String> params, TerminalRequestDTO terminalInfo) {
        if(params == null || terminalInfo ==null)
            return;

        params.put("terminalIP", terminalInfo.getTerminalIP());
        params.put("terminalInfo", terminalInfo.getTerminalInfo());
        params.put("terminalType", terminalInfo.getTerminalType());
    }

    private void getLogging(String path, String params, String flag) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "get method:{} , params:{} , flag[1->IOS,2->Android,3->PC]:{}",
                    path, params, flag);
        }
    }

    private String processHttpGet(String path, Map<String, String> map) {
        String result = utils.get(path, map);

        logger.info("Yingmi API GET : [{}] , params= {} , result= {}", path, map, result);
        yingmiApiRepo.store("GET", path, map.toString(), result);

        return result;
    }

    private String processHttpPost(Map<String, String> map, String path) {
        String result = utils.post(path, map);

        logger.info("Yingmi API POST : [{}] , params= {} , result= {}", path, map, result);
        yingmiApiRepo.store("POST", path, map.toString(), result);

        return result;
    }


    public ArrayList<Map> getArrayList(String JsonStr){
        try {
            ArrayList<Map> orderListMap = new ArrayList<>();
            if (this.isJsonArray(JsonStr)) {
                orderListMap = this.convertArrayToList(JsonStr);
            }else{
                Map oneMap = this.convertToMap(JsonStr);
                orderListMap.add(oneMap);
            }

            return orderListMap;
        } catch (IOException e) {
            logger.error("getProcSuccessAmount error" + e);
            return  null;
        }
    }

}
